package cn.virens.common.project.generator.database.beetl;

import cn.virens.common.project.generator.database.utils.PathUtil;
import cn.virens.common.util.core.objcet.ObjectUtil;
import cn.virens.common.util.exception.APIException;
import org.beetl.core.Format;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.text.StrUtil;

public class BeetlFtFormat implements Format {

    @Override
    public Object format(Object data, String pattern) throws APIException {
        if (pattern != null && pattern.equals("group")) {
            return group(ObjectUtil.toString(data));//
        }

        if (pattern != null && pattern.equals("perm")) {
            return perm(ObjectUtil.toString(data));//
        }

        if (pattern != null && pattern.equals("path")) {
            return path(ObjectUtil.toString(data));//
        }

        if (pattern != null && pattern.equals("pkg")) {
            return pkg(ObjectUtil.toString(data));//
        }

        if (data instanceof CharSequence) {
            return str(data.toString());
        } else {
            return data;
        }
    }

    private static String str(String str) throws APIException {
        return str.replaceAll("\"", "\\\\\"");
    }

    private static String pkg(String str) throws APIException {
        if (str != null && !str.isEmpty()) {
            return "." + str;
        } else {
            return "";
        }
    }

    private static String group(String str) throws APIException {
        str = FileUtil.normalize(StrUtil.replace(str, "-", "/"));

        str = StrUtil.removeSuffix(str, "/");
        str = StrUtil.removePrefix(str, "/");

        return str;
    }

    private static String path(String str) throws APIException {
        return PathUtil.path(str);
    }

    private static String perm(String str) throws APIException {
        return PathUtil.perm(str);
    }
}
